//
//  SSCarouselFigure.m
//  Travel_World
//
//  Created by dlios on 15/10/12.
//  Copyright © 2015年 TLS. All rights reserved.
//

#import "SSCarouselFigure.h"
#import "SSCarouselFigureCell.h"
#import "Masonry.h"

@implementation SSCarouselFigure

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    
    }
    return self;
}


- (void)createColletionViewByArr:(NSMutableArray *)arr;
{
    if (arr.count > 1) {
        
        self.arr = [NSMutableArray array];
        [self.arr addObject:arr[arr.count - 1]];
        
        for (NSString *temp in arr) {
            [self.arr addObject:temp];
        }
        
        [self.arr addObject:arr[0]];
        
    } else {
        
        self.arr = arr;
    }
    
    [self createCellectionView];
}


- (void)createCellectionView
{
    if (self.arr.count == 0) {
        return;
    }
    
    if (self.arr.count == 1) {
        
        if (!self.imageView) {
            
            self.imageView = [[UIImageView alloc] initWithFrame:self.frame];
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.arr[0]]];
            [self addSubview:self.imageView];
        }
 
    } else {
        
        if (!self.collectionView) {
            
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
            flowLayout.itemSize = self.frame.size;
            flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            flowLayout.minimumInteritemSpacing = 0;
            flowLayout.minimumLineSpacing = 0;
            
            self.collectionView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:flowLayout];
            self.collectionView.backgroundColor = [UIColor whiteColor];
            self.collectionView.showsHorizontalScrollIndicator = NO;
            self.collectionView.showsVerticalScrollIndicator = NO;
            self.collectionView.bounces = NO;
            self.collectionView.contentOffset = CGPointMake(self.frame.size.width, 0);
            
            self.collectionView.pagingEnabled = YES;
            [self addSubview: self.collectionView];
            
            self.collectionView.delegate = self;
            self.collectionView.dataSource = self;
            
            [self.collectionView registerClass:[SSCarouselFigureCell class] forCellWithReuseIdentifier:@"reuse"];
            
            [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.centerX.and.centerY.equalTo(self);
                make.width.and.height.equalTo(self);
                
            }];
            
        }
        
        if (!self.page) {
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aboutTimer:) name:@"timer" object:nil];
            
            self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(self.frame.size.width / 2, self.frame.size.height * 0.75, self.frame.size.width / 2, self.frame.size.height * 0.25)];
            [self addSubview:self.page];
            
            self.page.backgroundColor = [UIColor clearColor];
            self.page.pageIndicatorTintColor = [UIColor whiteColor];
            self.page.currentPageIndicatorTintColor = [UIColor greenColor];
            self.page.currentPage = 0;
            self.page.numberOfPages = self.arr.count - 2;
            self.page.userInteractionEnabled = NO;
            
            [self.page mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.left.equalTo(@(self.frame.size.width / 2));
                make.top.equalTo(@(self.frame.size.height * 0.75));
                make.width.equalTo(@(self.frame.size.width / 2));
                make.height.equalTo(@(self.frame.size.height * 0.25));

            }];

        }
        
        if (!self.timer) {
            
            self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
            
            [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
    }
}


- (void)aboutTimer:(NSNotification *)notification
{
    NSString *str = notification.userInfo[@"1"];
  
    if ([str isEqualToString:@"1"]) {

            
        [self addTimer];
      
    }
    
    if ([str isEqualToString:@"2"]) {
        [self removeTimer];
    }
}


- (void)changeImage
{
    
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x + self.frame.size.width, 0) animated:YES];
    
    
    if (self.collectionView.contentOffset.x / self.frame.size.width == self.arr.count - 1)
        self.collectionView.contentOffset = CGPointMake(self.frame.size.width, 0);
    
    if (self.collectionView.contentOffset.x / self.frame.size.width == self.arr.count - 2) {
        
        self.page.currentPage = 0;
        
    } else {
        self.page.currentPage = self.collectionView.contentOffset.x / self.frame.size.width;
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SSCarouselFigureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    if (self.arr.count > indexPath.row) {
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:self.arr[indexPath.row]] placeholderImage:[UIImage imageNamed:@"placeholder1"]];
    }
    
    return cell;
}


- (void)addTimer
{
    [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:3]];
}


- (void)removeTimer
{
    [self.timer setFireDate:[NSDate distantFuture]];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    if (scrollView == self.collectionView) {
        if (scrollView.contentOffset.x < 10) {
            scrollView.contentOffset = CGPointMake((self.arr.count - 2) * self.frame.size.width, 0);
        }
        
        if (scrollView.contentOffset.x > self.frame.size.width * (self.arr.count - 1) - 10 && scrollView.contentOffset.x < self.frame.size.width * (self.arr.count - 1) + 10) {
            scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
        }
        
        self.page.currentPage = scrollView.contentOffset.x / self.frame.size.width - 1;
        
        [self addTimer];
    }
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        [self.delegate clickCarouselFigureItem:self.arr.count - 3];

    } else if (indexPath.row == self.arr.count - 1){
        [self.delegate clickCarouselFigureItem:0];
    } else {
        [self.delegate clickCarouselFigureItem:indexPath.row - 1];
    }
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}


/*
 Only override drawRect: if you perform custom drawing.
 An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
     Drawing code
}
*/

@end
